package com.cloud.check.common.utils;

import com.aspose.words.Bookmark;
import com.aspose.words.BookmarkCollection;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;
import java.util.Map;

public class WordHelper {
	
	/**
	 * 替换word文档书签内容
	 * @param content
	 * @param params
	 * @return
	 */
	public static byte[] replaceBookMark(byte[] content, Map<String, String> params) {
		byte[] result = null;
		ByteArrayInputStream bis = null;
		ByteArrayOutputStream bos = null;
		Document doc = null;
		try {
			bis = new ByteArrayInputStream(content);
			doc = new Document(bis);
			BookmarkCollection bookMarks = doc.getRange().getBookmarks();
			@SuppressWarnings("unchecked")
			Iterator<Bookmark> it = bookMarks.iterator();
			while (it.hasNext()) {
				Bookmark mark = it.next();
				String markName = mark.getName();
				if (params.containsKey(markName)) {
					if (params.get(markName) != null) {
						String value = params.get(markName) + "";
						mark.setText(value);
					} else {
						mark.setText("");
					}
				}
			}
			bos = new ByteArrayOutputStream();
			doc.save(bos, SaveFormat.DOC);
			bos.flush();
			result = bos.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (null != bis) {
					bis.close();
				}
				if (null != bos) {
					bos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
}
